package org.zlb.algorithm.distance;

public class Pearson {

    /**
     * 皮尔逊相关系数
     * @param v1
     * @param v2
     * @return
     */
    public static double coefficient(double[] v1, double[] v2) {
        if (v1.length != v2.length)
            return -1;
        
        int n = v1.length;
        double sum_x = 0.0;
        double sum_y = 0.0;
        double sum_xy = 0.0;
        double sum_xx = 0.0;
        double sum_yy = 0.0;
        
        for (int i=0; i<v1.length; i++) {
            sum_x += v1[i];
            sum_y += v2[i];
            sum_xy += v1[i] * v2[i];
            sum_xx += v1[i] * v1[i];
            sum_yy += v2[i] * v2[i];
        }
        
        double numerator = sum_xy - (sum_x * sum_y) / n;
        double denominator = Math.sqrt((sum_xx - Math.pow(sum_x, 2)/n) * (sum_yy - Math.pow(sum_y, 2)/n));
        double r = numerator/ denominator;
        
        return r;
    }
    
}
